"""
状态工具函数
提供从状态管理模块获取状态的便捷方法
"""
from typing import Optional, List, Dict, Any
from motor.motor_asyncio import AsyncIOMotorDatabase
from app.core.state_cache import state_cache
from app.models.state import StateResponse


async def get_module_states(
    db: AsyncIOMotorDatabase,
    module_type: str,
    force_refresh: bool = False
) -> List[StateResponse]:
    """获取模块的所有状态"""
    return await state_cache.get_module_states(db, module_type, force_refresh)


async def get_state_by_code(
    db: AsyncIOMotorDatabase,
    module_type: str,
    code: str
) -> Optional[StateResponse]:
    """根据代码获取状态"""
    return await state_cache.get_state_by_code(db, module_type, code)


async def get_state_code_by_name_keywords(
    db: AsyncIOMotorDatabase,
    module_type: str,
    keywords: List[str]
) -> Optional[str]:
    """
    根据状态名称关键词获取状态代码
    例如：keywords=["已完成", "完成"] 会查找名称包含这些关键词的状态
    
    支持中英文关键词匹配，不区分大小写
    """
    states = await state_cache.get_module_states(db, module_type)
    keywords_lower = [k.lower() for k in keywords if k]
    
    for state in states:
        if state.is_enabled:
            state_name_lower = state.name.lower() if state.name else ""
            state_code_lower = state.code.lower() if state.code else ""
            
            for keyword in keywords_lower:
                # 匹配状态名称或状态代码
                if keyword in state_name_lower or keyword == state_code_lower:
                    return state.code
    return None


async def get_completed_state_code(
    db: AsyncIOMotorDatabase,
    module_type: str
) -> Optional[str]:
    """获取"已完成"状态的代码"""
    return await get_state_code_by_name_keywords(
        db, module_type, ["已完成", "完成", "completed"]
    )


async def get_active_state_code(
    db: AsyncIOMotorDatabase,
    module_type: str
) -> Optional[str]:
    """获取"进行中"/"活跃"状态的代码"""
    return await get_state_code_by_name_keywords(
        db, module_type, ["进行中", "活跃", "active", "in_progress"]
    )


async def validate_state_code(
    db: AsyncIOMotorDatabase,
    module_type: str,
    code: str
) -> bool:
    """验证状态代码是否有效"""
    return await state_cache.validate_state_code(db, module_type, code)


async def get_state_options(
    db: AsyncIOMotorDatabase,
    module_type: str
) -> List[Dict[str, Any]]:
    """获取状态选项（用于前端下拉框）"""
    return await state_cache.get_state_options(db, module_type)


async def get_default_state_code(
    db: AsyncIOMotorDatabase,
    module_type: str
) -> Optional[str]:
    """获取默认状态代码"""
    default_state = await state_cache.get_default_state(db, module_type)
    return default_state.code if default_state else None


async def get_completed_state_codes(
    db: AsyncIOMotorDatabase,
    module_type: str
) -> List[str]:
    """
    获取所有完成状态的代码列表
    包括：已完成、已实现、已取消、已关闭等
    """
    keywords_list = [
        ["已完成", "完成", "completed", "done"],
        ["已实现", "实现", "implemented"],
        ["已取消", "取消", "cancelled"],
        ["已关闭", "关闭", "closed"],
        ["已解决", "解决", "resolved"],
    ]
    
    completed_codes = []
    for keywords in keywords_list:
        code = await get_state_code_by_name_keywords(db, module_type, keywords)
        if code and code not in completed_codes:
            completed_codes.append(code)
    
    return completed_codes

